package ldh.im.base.util;

import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

import java.io.InputStream;
import java.util.Properties;

public class MongodbUtil {

    private static MongoClient mongoClient = null;
    private static final String MONGO_CONFIG = "/mongo.properties";
    private static Properties MONGO_PROPERTIES;

    static {
        init();
    }

    public static MongoClient getMongoClient() {
        String type = getParam("mongo.type");
        if (type.equalsIgnoreCase("single")) {
            String url = getParam("mongo.url");
            int port = Integer.parseInt(getParam("mongo.port"));
            int timeout = Integer.parseInt(getParam("mongo.timeout"));
            String userName = getParam("mongo.userName");
            String password = getParam("mongo.password");
            String dbName = getParam("mongo.dbName");
            int db = Integer.parseInt(getParam("redis.db"));
            if (mongoClient == null) {
                synchronized (RedisUtil.class) {
                    if (mongoClient == null) {
                        MongoCredential mongoCredential = MongoCredential.createCredential(userName, dbName, password.toCharArray());
                        MongoClientSettings mongoClientSettings = MongoClientSettings.builder().credential(mongoCredential).build();
                        mongoClient = MongoClients.create(mongoClientSettings);
                    }
                }
            }
            return mongoClient;
        }
        return null;
    }

    public static void close() {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }

    private static void init() {
        try (InputStream inputStream = MongodbUtil.class.getResourceAsStream(MONGO_CONFIG)) {
            MONGO_PROPERTIES = new Properties();
            MONGO_PROPERTIES.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getParam(String key) {
        String value = MONGO_PROPERTIES.getProperty(key);
        if (value == null) {
            throw new RuntimeException("缺少参数：" + key);
        }
        return value;
    }
}
